package com.shihan.rabbitmq.consumer;

import com.rabbitmq.client.*;
import com.shihan.rabbitmq.utils.ConnUtil;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Description 消息消费手动确认
 * @Author shihan
 * @Date 2021/1/2 17:28
 * @Version 1.0
 */
public class ManualACK {

    public static final String QUEUE_NAME_TEMP = "queue.temp.name";

    public static void main(String[] args) throws URISyntaxException, IOException, TimeoutException, NoSuchAlgorithmException, KeyManagementException {

        Channel channel = ConnUtil.getChannel();

        // 消费端指明队列即可
        channel.queueDeclare(QUEUE_NAME_TEMP,false,false,false,null);

        // 原生 API 的方式手动确认消息
        // autoAck 设为 false
        // TODO consumerTag 是干嘛用的
        channel.basicConsume(QUEUE_NAME_TEMP,false,"myConsumer",new DefaultConsumer(channel) {

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                // 将消息进行打印
                System.out.println("【接收到的消息】：" + new String(body,"utf-8"));

                // 手动确认消息
                // channel.basicAck(envelope.getDeliveryTag(),false);

                // 手动不确认消息：可以拒收多条消息
                // deliveryTag、是否确认之前的消息、失败是否重新入队并重发
                // channel.basicNack(envelope.getDeliveryTag(), false, true);

                // 手动拒收消息：一条消息
                channel.basicReject(envelope.getDeliveryTag(),true);

            }
        });

        // 延迟一会儿，不让 channel 和 connection 关闭
        // ConnUtil.closeConn();
    }

}

class ProducerForCurr {

    public static final String EXCHANGE_NAME_TEMP = "exc.direct.temp.name";

    public static final String QUEUE_NAME_TEMP = "queue.temp.name";

    public static final String BINDING_KEY_TEMP = "direct.temp.key";

    public static void main(String[] args) throws URISyntaxException, IOException, TimeoutException, NoSuchAlgorithmException, KeyManagementException {
        Channel channel = ConnUtil.getChannel();

        channel.queueDeclare(QUEUE_NAME_TEMP,false,false,false,null);
        channel.exchangeDeclare(EXCHANGE_NAME_TEMP, BuiltinExchangeType.DIRECT);
        channel.queueBind(QUEUE_NAME_TEMP,EXCHANGE_NAME_TEMP,BINDING_KEY_TEMP);

        for (int i = 0; i < 5; i++) {
            channel.basicPublish(EXCHANGE_NAME_TEMP,BINDING_KEY_TEMP,null,("测试手动确认，发送的消息" + i).getBytes("utf-8"));
        }

        ConnUtil.closeConn();
    }

}
